/**
 * @name: 折线图
 * @return {*}
 */
import { cloneDeep } from 'lodash';

export const useLint = (api: Function | Array<Function>, obj: any, field?: string) => {
  let lintOption: any = reactive({
    xAxis: {
      type: 'category',
      data: []
    },
    grid: {
      x: isMobile() ? 50 : '10%',
      right: isMobile() ? 10 : '10%'
    },
    title: {
      text: obj.title,
      left: 'center',
      top: '10',
      textStyle: {
        color: '#000',
        fontSize: 16
      }
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        data: [],
        label: {
          show: true,
          position: 'top',
          formatter: function (params: any) {
            return params.value.toLocaleString();
          }
        },
        type: 'line'
      }
    ]
  });

  let loading = ref(false);
  const getData = (params: any) => {
    let series = cloneDeep(lintOption.series);

    loading.value = true;

    lintOption.xAxis.data = [];

    if (Array.isArray(api)) {
      lintOption.series.data = [];
      api.forEach((sonApi: Function, index: number) => {
        sonApi({ ...params[index] })
          .then((data: any) => {
            const f = (field || 'key,value').split(',');
            if (!obj.params?.series) {
              lintOption.series[index] = cloneDeep(series[index]);
            } else {
              lintOption.series[index] = cloneDeep(obj.params?.series[index]);
            }

            data.forEach((item: any) => {
              if (index === 0) {
                lintOption.xAxis.data.push(item[f[0]]);
              }
              lintOption.series[index].data.push(item[f[1]]);
            });

            loading.value = false;
          })

          .catch(() => {
            loading.value = false;
          });
      });
    } else {
      console.log(params, 'params');

      api(params)
        .then((data: any) => {
          lintOption.series[0].data = [];
          const f = (field || 'key,value').split(',');

          data.forEach((item: any) => {
            lintOption.xAxis.data.push(item[f[0]]);
            lintOption.series[0].data.push(item[f[1]]);
          });
          loading.value = false;
          console.log(lintOption, 'lintOption');
        })
        .catch(() => {
          loading.value = false;
        });
    }
  };

  onBeforeMount(() => {
    if (obj.params) {
      Object.keys(obj.params).forEach(key => {
        if (!lintOption[key]) {
          lintOption[key] = obj.params[key];
        } else {
          Object.assign(lintOption[key], obj.params[key]);
        }
      });
    }
  });
  return {
    lintOption,
    loading,
    getData
  };
};
